package cn.tedu.gateway.Predicate;

import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component //将Bean管理的权限交给spring
public class AgeRoutePredicateFactory extends
        AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

   public AgeRoutePredicateFactory(){
       super(AgeRoutePredicateFactory.Config.class);
   }
   /*绑定静态内部类：用于从配置文件中接受参数属性*/
   @Override
   public List<String> shortcutFieldOrder(){
       //这里的顺序要跟配置文件中的属性顺序一致
       return Arrays.asList("minAge","maxAge");
   }
   /*断言逻辑代码*/
    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config){
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //1.接收前台传入的参数
                String ageKey = serverWebExchange.getRequest().getQueryParams().getFirst("age");
                //2.判断age是否为空
                if(StringUtils.isNotEmpty(ageKey)){
                    //age不为空，获取age对应的值
                    //判断age的值是否在配置文件指定的范围内，在指定的范围内返回true
                    int ageValue = Integer.parseInt(ageKey);
                    if(ageValue < config.getMaxAge() && ageValue > config.getMinAge())
                        return true;
                    //不在指定的年龄范围内，返回false
                    return false;
                }
                return false;
            }
        };
    }
    /*静态内部类，主要是接受配置文件中的信息*/
    public static class Config{
        private int minAge;
        private int maxAge;

        public Config(){

        }

        public int getMinAge() {
            return minAge;
        }

        public void setMinAge(int minAge) {
            this.minAge = minAge;
        }

        public int getMaxAge() {
            return maxAge;
        }

        public void setMaxAge(int maxAge) {
            this.maxAge = maxAge;
        }
    }
}
